package com.frogs.ucenter.v1.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.frogs.api.wechat.util.TemplateUtil;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.AttentionStateEnum;
import com.frogs.system.util.DataTypeInfoEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.dao.UserAttentionInfoDao;
import com.frogs.ucenter.dao.UserPraiseInfoDao;
import com.frogs.ucenter.dao.WechatUserBaseInfoDao;
import com.frogs.ucenter.entity.UserPraiseInfo;
import com.frogs.ucenter.entity.WechatUserBaseInfo;
import com.frogs.ucenter.entity.ext.UserPersonInfoExt;
import com.frogs.ucenter.util.wechat.WechatMessageSend;
import com.frogs.ucenter.v1.request.UserAttentionPraiseInfoRequest;
import com.frogs.ucenter.v1.request.UserAttentionPraiseListRequest;
import com.frogs.ucenter.v1.request.UserPersonalPraiseListRequest;
import com.frogs.ucenter.v1.request.UserPraiseInfoAddRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.PageListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.service.UserPraiseInfoService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userPraiseInfoService")
public class UserPraiseInfoServiceImpl implements UserPraiseInfoService {
	
	private static final Logger log = LoggerFactory.getLogger(UserPraiseInfoServiceImpl.class);
	
	@Resource
	private UserPraiseInfoDao userPraiseInfoDao;
	@Resource
	private UserAttentionInfoDao userAttentionInfoDao;
	@Resource
	private WechatUserBaseInfoDao wechatUserBaseInfoDao;
	@Resource
	private RequestApiHelper requestApiHelper;
	@Resource
	private WechatMessageSend wechatMessageSend;
	
	@Override
	public Response getAttentionPraiseList(Request request) throws Exception  {
		ShowResponse<Map<Integer, Object>> response = new ShowResponse<Map<Integer, Object>>();
		try {
			UserAttentionPraiseListRequest listRequest = (UserAttentionPraiseListRequest) request;
			Integer userId = listRequest.getUserId();
			Integer openPlatformId = listRequest.getOpenPlatformId();
			Integer type = listRequest.getType();
			String dataIds = listRequest.getDataIds();
			Map<Integer, Object> result = new HashMap<Integer, Object>();
			String[] dataIdList = dataIds.split(",");
			for (int i = 0; i < dataIdList.length; i++) {
				JSONObject object = new JSONObject();
				Integer dataId = Integer.valueOf(dataIdList[i]);
				HashMap<String,Object> params = new HashMap<String,Object>();
				params.put("eqDataId", dataId);
				params.put("eqType", type);
				params.put("eqOpenPlatformId", openPlatformId);
				params.put("initiateUserId", userId);
				Map<String, Object> map = userPraiseInfoDao.selectPraiseByMap(params);
				if (map != null) {
					if (!StringUtil.isEmpty(map.get("receiveUserId"))) {
						object.putAll(map);
						result.put((Integer) map.get("receiveUserId"), object);
					}
				}
			}
    		response.setInfo(result);
    		response.setTip("查询成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	@Override
	public Response getAttentionPraiseInfo(Request request) throws Exception  {
		ShowResponse<JSONObject> response = new ShowResponse<JSONObject>();
		try {
			UserAttentionPraiseInfoRequest infoRequest = (UserAttentionPraiseInfoRequest) request;
			JSONObject result = new JSONObject();
			Integer userId = infoRequest.getUserId();
			Integer followedUserId = infoRequest.getFollowedUserId();
			Integer openPlatformId = infoRequest.getOpenPlatformId();
			Integer type = infoRequest.getType();
			Integer dataId = infoRequest.getDataId();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqOpenPlatformId", openPlatformId);
			params.put("eqReceiveUserId", followedUserId);
			params.put("eqType", type);
			params.put("eqDataId", dataId);
			params.put("initiateUserId", userId);
			Map<String, Object> map = userPraiseInfoDao.selectPraiseByMap(params);
			if (map == null) {
				result.put("praiseCount", 0);
				result.put("isPraise", 0);
			} else {
				result.putAll(map);
			}
			response.setInfo(result);
			response.setTip("查询成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	@Override
	public Response insertPraise(Request request) {
		AddResponse<UserPraiseInfo> response = new AddResponse<UserPraiseInfo>();
		try {
			UserPraiseInfoAddRequest addRequset = (UserPraiseInfoAddRequest)request;
			Integer followedUserId = addRequset.getFollowedUserId();
			Integer userId = addRequset.getUserId();
			Integer openPlatformId = addRequset.getOpenPlatformId();
			Integer type = addRequset.getType();
			Integer dataId = addRequset.getDataId();
			String message =  addRequset.getMessage();
			Map<String,Object> params = new HashMap<String , Object>();
			params.put("eqReceiveUserId", followedUserId);
			params.put("eqInitiateUserId", userId);
			params.put("eqOpenPlatformId", openPlatformId);
			params.put("eqType", type);
			params.put("eqDataId", dataId);
			PageList<UserPraiseInfo> list = userPraiseInfoDao.selectByMap(params, false);
            if(list.size()==0){
    			UserPraiseInfo userPraiseInfo = new UserPraiseInfo();
    			userPraiseInfo.setInitiateUserId(userId);
    			userPraiseInfo.setReceiveUserId(followedUserId);
    			userPraiseInfo.setOpenPlatformId(openPlatformId);
    			userPraiseInfo.setDataId(dataId);
    			userPraiseInfo.setType(type);
    			userPraiseInfo.setMessage(message); 
    			userPraiseInfoDao.insert(userPraiseInfo);
    			response.setInfo(userPraiseInfo);
    			response.setTip("点赞成功");
    			params.clear();
    			params.put("eqUserId", addRequset.getUserId());  
    			params.put("eqWechatApplicationId", addRequset.getOpenPlatformId());
    			PageList<WechatUserBaseInfo> userList = wechatUserBaseInfoDao.selectByMap(params, false);
    			WechatUserBaseInfo wechatUserBaseInfo = userList.get(0);
    			//TODO是否需要修改文案
    			Map<Integer,String> dataTypeInfo = DataTypeInfoEnum.listAllTypes();
    			String project = dataTypeInfo.get(type);
    			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?&redirect_uri=http%3A%2F%2Fw.frogshealth.com%2Fuser%2Fpraise%2Flist.html%3FuserId%3D"+followedUserId+"%26type%3D"+type+"%26dataId%3D"+dataId+"&appid=wxb30222354415be84&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    			String remark = "";
    			if (type == 4) {
    				remark = wechatUserBaseInfo.getNickName()+"刚刚为您今天的运动成果点赞了！";
    			} else {
    				remark = wechatUserBaseInfo.getNickName()+"刚刚赞了你的"+project+"测量结果";
    			}
    			String keyword = "点赞通知";
    			String messageStr = TemplateUtil.convert(url, keyword, remark);
    			Integer followUserId = wechatUserBaseInfo.getUserId();
    			wechatMessageSend.send(followedUserId, followUserId, messageStr, openPlatformId);
            }else{
				response.setTip("您已点赞过");
				response.setCode(ApiResultEnum.FAIL.getId());
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
	@Override
	public Response getPersonalPraiseInfo(Request request) throws Exception  {
		PageListResponse<UserPersonInfoExt> response = new PageListResponse<UserPersonInfoExt>();
		try {
			UserPersonalPraiseListRequest listRequest = (UserPersonalPraiseListRequest) request;
			Integer userId = listRequest.getUserId();
			HashMap<String,Object> params = new HashMap<String,Object>();
			params.put("eqReceiveUserId", userId);
			params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
			params.put("eqOpenPlatformId", listRequest.getOpenPlatformId());
			params.put("eqType", listRequest.getType());
			params.put("eqDataId", listRequest.getDataId());
    		params.put("orderByClause"," create_time DESC" );
    		PageList<UserPersonInfoExt> list = userPraiseInfoDao.selectByMapForPerson(params, listRequest.getPageNo(), listRequest.getPageSize());
    		response.setList(list);
    		response.setPageTurn(list.getPageTurn());
    		response.setTip("查询成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
}